package com.yfqy.app.modules.product.serviceimpl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yfqy.app.domain.entity.ProductSpuImages;
import com.yfqy.app.domain.mapper.ProductSkuMapper;
import com.yfqy.app.domain.mapper.ProductSpuImagesMapper;
import com.yfqy.app.domain.mapper.ProductSpuMapper;
import com.yfqy.app.enums.ErrorCode;
import com.yfqy.app.exception.BusinessException;
import com.yfqy.app.modules.product.dto.ProductQueryDTO;
import com.yfqy.app.modules.product.service.ProductService;
import com.yfqy.app.modules.product.vo.ProductSkuVO;
import com.yfqy.app.modules.product.vo.ProductSpuVO;
import com.yfqy.app.transform.CategoryNameTranslator;
import com.yfqy.app.transform.LabelNameTranslator;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {


    @Resource
    private ProductSpuMapper productSpuMapper;
    @Resource
    private ProductSkuMapper productSkuMapper;
    @Resource
    private LabelNameTranslator labelNameTranslator;
    @Resource
    private CategoryNameTranslator categoryNameTranslator;
    @Resource
    private ProductSpuImagesMapper productSpuImagesMapper;


    @Override
    public ProductSpuVO detail(Long id) {
        ProductSpuVO spuVO = productSpuMapper.selectSpuVOById(id);
        if (spuVO == null) {
            throw new BusinessException(ErrorCode.PRODUCT_NOT_EXIST_ERROR);
        }
        labelNameTranslator.translationLabel(spuVO);
        categoryNameTranslator.translationCategory(spuVO);
        List<ProductSkuVO> skus = skuList(id);
        ProductSpuImages spuImages = productSpuImagesMapper.selectByPrimaryKey(id);
//        spuVO.setMainImageList(Arrays.asList(spuImages.getMainImages().split(",")));
//        spuVO.getMainImageList().addAll(Arrays.asList(spuImages.getDetailImages().split(",")));
        // 合并处理主图和详情图（如果业务确实需要）
        List<String> allImages = Stream.of(
                        Optional.ofNullable(spuImages.getMainImages()).orElse(""),
                        Optional.ofNullable(spuImages.getDetailImages()).orElse("")
                )
                .flatMap(images -> Arrays.stream(images.split(",")))
                .filter(StringUtils::isNotBlank)
                .map(String::trim)
                .collect(Collectors.toList());
        spuVO.setMainImageList(allImages);
        spuVO.setProductSkus(skus);
        return spuVO;
    }


    @Override
    public PageInfo<ProductSpuVO> products(ProductQueryDTO productQuery) {
        // 参数验证
        validateProductQuery(productQuery);

        PageHelper.startPage(productQuery.getPageIndex(), productQuery.getPageSize());
        try {
            List<ProductSpuVO> spuVOS = productSpuMapper.selectPageListByCondition(productQuery);
            if (CollUtil.isEmpty(spuVOS)) {
                log.info("未查询到商品数据，查询条件: {}", productQuery);
                return new PageInfo<>(Collections.emptyList());
            }

            // 批量处理商品信息
            enrichProductSpuInfo(spuVOS);

            return new PageInfo<>(spuVOS);
        } catch (Exception e) {
            log.error("查询商品列表异常，查询条件: {}", productQuery, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR.getCode(), "商品查询失败");
        } finally {
            PageHelper.clearPage();
        }
    }

    /**
     * 验证查询参数
     */
    private void validateProductQuery(ProductQueryDTO productQuery) {
        if (productQuery.getPageIndex() == null || productQuery.getPageIndex() < 1) {
            productQuery.setPageIndex(1);
        }
        if (productQuery.getPageSize() == null || productQuery.getPageSize() < 1) {
            productQuery.setPageSize(20);
        }
    }

    /**
     * 批量丰富商品信息
     */
    private void enrichProductSpuInfo(List<ProductSpuVO> spuVOS) {
        List<Long> spuIds = spuVOS.stream()
                .map(ProductSpuVO::getId)
                .collect(Collectors.toList());

        // 并行批量查询，提高性能
        Map<Long, String> spuMainImageMap = batchGetMainImages(spuIds);
        Map<Long, List<ProductSkuVO>> spuSkuMap = batchGetSkus(spuIds);

        // 翻译分类名称
        categoryNameTranslator.translationCategory(spuVOS);
        labelNameTranslator.translationLabel(spuVOS);

        // 设置商品详细信息
        spuVOS.forEach(spuVO -> setSpuDetailInfo(spuVO, spuMainImageMap, spuSkuMap));
    }

    /**
     * 批量获取商品主图
     */
    private Map<Long, String> batchGetMainImages(List<Long> spuIds) {
        if (CollUtil.isEmpty(spuIds)) {
            return Collections.emptyMap();
        }

        List<ProductSpuImages> productSpuImages = productSpuImagesMapper.selectMainImagesBySpuIds(spuIds);
        return productSpuImages.stream()
                .collect(Collectors.toMap(
                        ProductSpuImages::getId,
                        this::extractFirstMainImage,
                        (existing, replacement) -> existing  // 重复key处理
                ));
    }

    /**
     * 提取第一张主图
     */
    private String extractFirstMainImage(ProductSpuImages spuImages) {
        if (spuImages == null || StringUtils.isBlank(spuImages.getMainImages())) {
            return "";
        }

        String[] images = spuImages.getMainImages().split(",");
        return images.length > 0 ? images[0].trim() : "";
    }

    /**
     * 批量获取SKU信息
     */
    private Map<Long, List<ProductSkuVO>> batchGetSkus(List<Long> spuIds) {
        if (CollUtil.isEmpty(spuIds)) {
            return Collections.emptyMap();
        }

        List<ProductSkuVO> productSkus = productSkuMapper.selectSkusBySpuIds(spuIds);
        return productSkus.stream()
                .collect(Collectors.groupingBy(ProductSkuVO::getSpuId));
    }

    /**
     * 设置商品详细信息
     */
    private void setSpuDetailInfo(ProductSpuVO spuVO,
                                  Map<Long, String> spuMainImageMap,
                                  Map<Long, List<ProductSkuVO>> spuSkuMap) {
        // 设置主图
        String mainImage = spuMainImageMap.getOrDefault(spuVO.getId(), "");
        spuVO.setMainImage(mainImage);

        // 设置SKU相关信息
        List<ProductSkuVO> skus = spuSkuMap.get(spuVO.getId());
        if (CollUtil.isNotEmpty(skus)) {
            spuVO.setSkuCount(skus.size());

            // 找到价格最低的SKU
            ProductSkuVO minPriceSku = findMinPriceSku(skus);
            spuVO.setUnitPrice(minPriceSku.getPrice());

            // 计算总销量
            int totalSales = calculateTotalSales(skus);
            spuVO.setTotalSales(totalSales);
        } else {
            // 没有SKU时的默认值
            spuVO.setSkuCount(0);
            spuVO.setUnitPrice(BigDecimal.ZERO);
            spuVO.setTotalSales(0);
        }
    }

    /**
     * 找到价格最低的SKU
     */
    private ProductSkuVO findMinPriceSku(List<ProductSkuVO> skus) {
        return skus.stream()
                .min(Comparator.comparing(ProductSkuVO::getPrice))
                .orElseThrow(() -> new BusinessException(ErrorCode.SYSTEM_ERROR.getCode(), "未找到有效的SKU价格"));
    }

    /**
     * 计算总销量
     */
    private int calculateTotalSales(List<ProductSkuVO> skus) {
        return skus.stream()
                .mapToInt(sku -> {
                    // 处理美化销量，确保不为null
                    Integer beautifySales = sku.getBeautifySales();
                    return beautifySales != null ? beautifySales : 0;
                })
                .sum();
    }

    @Override
    public List<ProductSkuVO> skuList(Long spuId) {
        return productSkuMapper.selectSkuVOsBySpuId(spuId);
    }

    @Override
    public List<ProductSpuVO> more(Long productId, ProductQueryDTO dto) {
        List<ProductSpuVO> spuVOList = products(dto).getList();
        if (!spuVOList.isEmpty()) {
            return spuVOList.stream().filter(vo -> !vo.getId().equals(productId)).toList();
        }
        return spuVOList;
    }

}
